﻿using MultiDAQ_Analysis.Util;
using MultiDAQ_Analysis.View;
using OxyPlot;
using OxyPlot.Axes;
using OxyPlot.Legends;
using OxyPlot.Series;
using OxyPlot.WindowsForms;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using TickStyle = OxyPlot.Axes.TickStyle;

namespace MultiDAQ_Analysis.View
{

    public partial class PlotViewPanel : UserControl
    {
        public PlotModel plotModel;
        private List<LineSeries> channelSeries;
        private Dictionary<int, Dictionary<double, int>> voltageStats;
        private PlotView plotView1;

        // 手动模式控制变量
        private DateTime lastManualOperationTime = DateTime.MinValue;
        private bool isManualMode = false;

        private double binSize = 0.01;
        private double voltageMin = 0.00;
        private double voltageMax = 1.75;
        private int channelCount = AppConfig.ChannelCount;

       
        private int currentChannelIndex = 0;

        private List<double> voltageBins;
        private Random random;
        private Timer simulationTimer;
        private Timer channelSwitchTimer;

        public PlotViewPanel()
        {
            InitializeComponent();
            random = new Random();
            InitVoltageHistogram();
            //StartSimulation();
            //StartChannelSwitching();
        }

        private void InitVoltageHistogram()
        {

            var colors = AppConfig.GetOxyChannelColors();

            // 初始化电压区间
            voltageBins = new List<double>();
            for (double v = voltageMin; v <= voltageMax; v += binSize)
            {
                voltageBins.Add(Math.Round(v, 3));
            }

            // 初始化统计数据
            voltageStats = new Dictionary<int, Dictionary<double, int>>();
            for (int i = 0; i < channelCount; i++)
            {
                voltageStats[i] = new Dictionary<double, int>();
                foreach (var bin in voltageBins)
                {
                    voltageStats[i][bin] = 0;
                }
            }

            // 创建PlotModel
            plotModel = new PlotModel
            {
                Title = $"通道 {currentChannelIndex + 1} - 电压分布",
                TitleFontSize = 13, // 设置标题字体大小（单位：点pt）
                IsLegendVisible = true,
                Background = OxyColors.White,
                PlotAreaBorderColor = OxyColors.Transparent,
                PlotAreaBorderThickness = new OxyThickness(0)
            };

            // 图例
            plotModel.Legends.Add(new Legend
            {
                LegendTitle = "通道",
                LegendPosition = LegendPosition.RightTop,
                LegendPlacement = LegendPlacement.Outside,
                // 新增这些设置来缩小图例
        LegendMaxWidth = 80,          // 限制图例最大宽度
                LegendMaxHeight = 200,        // 限制图例最大高度
                LegendMargin = 5,             // 图例边距
                LegendPadding = 3,            // 图例内边距
                LegendItemSpacing = 2,        // 图例项之间的间距
                LegendSymbolLength = 12,      // 图例符号长度
                LegendSymbolMargin = 4,       // 图例符号边距
                LegendFontSize = 10,          // 字体大小
                LegendTextColor = OxyColors.Black,
                LegendOrientation = LegendOrientation.Vertical // 垂直排列
            });

            // X轴
            plotModel.Axes.Add(new LinearAxis
            {
                Position = AxisPosition.Bottom,
                Title = "电压(V)",
                Minimum = voltageMin,
                Maximum = voltageMax,
                MajorGridlineStyle = LineStyle.Solid,
                MajorGridlineColor = OxyColors.LightGray,
                MinorGridlineStyle = LineStyle.Dot,
                MinorGridlineColor = OxyColors.LightGray,
                TickStyle = TickStyle.Outside,
                MajorStep = 0.5,
                StringFormat = "0.0"
            });

            // Y轴
            plotModel.Axes.Add(new LinearAxis
            {
                Position = AxisPosition.Left,
                Title = "频次",
                Minimum = 0,
                Maximum = 50,
                MajorGridlineStyle = LineStyle.Solid,
                MajorGridlineColor = OxyColors.LightGray,
                MinorGridlineStyle = LineStyle.Dot,
                MinorGridlineColor = OxyColors.LightGray,
                TickStyle = TickStyle.Outside
            });

            // 颜色数组
            //OxyColor[] colors = new OxyColor[]
            //{
            //    OxyColors.LimeGreen, OxyColors.DodgerBlue, OxyColors.Crimson, OxyColors.Orange,
            //    OxyColors.Purple, OxyColors.Teal, OxyColors.Brown, OxyColors.HotPink,
            //    OxyColors.Magenta, OxyColors.Cyan, OxyColors.Yellow, OxyColors.Gray
            //};

            // 创建所有通道的LineSeries
            channelSeries = new List<LineSeries>();
            for (int i = 0; i < channelCount; i++)
            {
                var series = new LineSeries
                {
                    Title = $"通道 {i + 1}",
                    Color = colors[i % colors.Length],
                    StrokeThickness = 2,
                    LineStyle = LineStyle.Solid,
                    MarkerType = MarkerType.None,
                    IsVisible = (i == currentChannelIndex), // 只显示当前通道
                    // 设置工具提示格式
                    TrackerFormatString = "通道: {Title}\n电压: {2:F2}V\n频次: {4:F0}"
                };

                plotModel.Series.Add(series);
                channelSeries.Add(series);
            }

            // 创建PlotView
            if (plotView1 == null)
            {
                plotView1 = new PlotView
                {
                    Dock = DockStyle.Fill,
                    Model = plotModel
                };
                this.Controls.Add(plotView1);
            }
            else
            {
                plotView1.Model = plotModel;
            }
            //plotModel.DefaultColors = colors;
            //plotView1.Model = plotModel;

            // 设置工具提示格式
            //plotView1.ActualModel.TrackerFormatString = "电压: {2:0.00}V\n频次: {4:0}";

            plotModel.InvalidatePlot(true);
        }


        public void StartChannelSwitching()
        {
            channelSwitchTimer = new Timer { Interval = 4000 }; // 4秒切换间隔
            channelSwitchTimer.Tick += (s, e) => {
                // 检查是否需要从手动模式恢复
                if (isManualMode && DateTime.Now - lastManualOperationTime >= TimeSpan.FromSeconds(10))
                {
                    isManualMode = false; // 10秒后自动恢复
                    plotModel.Title = $"通道 {currentChannelIndex + 1} - 电压分布 (已恢复自动模式)";
                }

                // 只有非手动模式才执行自动切换
                if (!isManualMode)
                {
                    SwitchToNextChannel();
                }
            };
            channelSwitchTimer.Start();
        }

        private void SwitchToNextChannel()
        {
            currentChannelIndex = (currentChannelIndex + 1) % channelCount;
            plotModel.Title = $"通道 {currentChannelIndex + 1} - 电压分布";

            // 只显示当前通道
            for (int i = 0; i < channelSeries.Count; i++)
            {
                channelSeries[i].IsVisible = (i == currentChannelIndex);
            }

            UpdateHistogram();
        }





        public void AddVoltagePoint(int channelIndex, double voltage)
        {
            if (channelIndex < 0 || channelIndex >= channelCount) return;
            if (voltage < voltageMin || voltage > voltageMax) return;

            // 更精确的bin计算
            int binIndex = (int)Math.Round(voltage / binSize);
            double bin = binIndex * binSize;
            bin = Math.Round(bin, 3); // 确保精确到3位小数

            if (voltageStats[channelIndex].ContainsKey(bin))
            {
                voltageStats[channelIndex][bin]++;
            }
        }

        public void UpdateHistogram()
        {
            int maxCount = 0;
            bool hasData = false;

            // 更新所有通道的数据
            for (int ch = 0; ch < channelSeries.Count; ch++)
            {
                channelSeries[ch].Points.Clear();
                var currentChannelData = voltageStats[ch];

                // 按顺序添加所有数据点
                foreach (var bin in voltageBins)
                {
                    int count = currentChannelData.ContainsKey(bin) ? currentChannelData[bin] : 0;

                    if (count > maxCount) maxCount = count;
                    if (count > 0) hasData = true;

                    channelSeries[ch].Points.Add(new DataPoint(bin, count));
                }
            }

            // 动态调整Y轴范围
            var yAxis = plotModel.Axes[1] as LinearAxis;
            if (yAxis != null)
            {
                yAxis.Maximum = hasData ? Math.Max(maxCount * 1.1, 5) : 5;
                yAxis.Minimum = 0;
            }

            plotModel.InvalidatePlot(true);
        }

        // 保留原有的业务函数 - 修正版本
        public void ShowOnlyChannel(int channelIndex)
        {
            isManualMode = true;
            lastManualOperationTime = DateTime.Now;

            if (channelIndex < 0 || channelIndex >= channelSeries.Count) return;

            // 不要停止定时器，让它继续运行以便自动恢复
            currentChannelIndex = channelIndex;
            plotModel.Title = $"通道 {channelIndex + 1} - 电压分布 (手动模式，10秒后自动恢复)";

            for (int i = 0; i < channelSeries.Count; i++)
                channelSeries[i].IsVisible = (i == channelIndex);

            plotModel.InvalidatePlot(true);
        }

        public void HideAllChannels()
        {
            isManualMode = true;
            lastManualOperationTime = DateTime.Now;

            foreach (var s in channelSeries)
                s.IsVisible = false;

            plotModel.Title = "电压分布 - 所有通道已隐藏 (手动模式，10秒后自动恢复)";
            plotModel.InvalidatePlot(true);
        }




        // 工具方法
        public void StopChannelSwitching()
        {
            if (channelSwitchTimer != null)
            {
                channelSwitchTimer.Stop();
                channelSwitchTimer.Dispose();
                channelSwitchTimer = null;
            }
        }


        public void StopSimulation()
        {
            if (simulationTimer != null)
            {
                simulationTimer.Stop();
                simulationTimer.Dispose();
                simulationTimer = null;
            }
        }

        public void ClearAllData()
        {
            foreach (var channelDict in voltageStats.Values)
            {
                var keys = channelDict.Keys.ToList();
                foreach (var key in keys)
                {
                    channelDict[key] = 0;
                }
            }
            UpdateHistogram();
        }



        // 获取当前模式状态
        public bool IsManualMode => isManualMode;

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                StopSimulation();
                StopChannelSwitching();
            }
            base.Dispose(disposing);
        }
        public void AddVoltagePointsBatch(int channelIndex, List<double> voltages)
        {
            if (channelIndex < 0 || channelIndex >= channelCount || voltages == null || voltages.Count == 0)
                return;

            lock (voltageStats) // 确保线程安全
            {
                foreach (double voltage in voltages)
                {
                    if (voltage >= voltageMin && voltage <= voltageMax)
                    {
                        double bin = Math.Round(voltage / binSize) * binSize;
                        bin = Math.Round(bin, 3);

                        if (voltageStats[channelIndex].ContainsKey(bin))
                        {
                            voltageStats[channelIndex][bin]++;
                        }
                    }
                }
            }
        }
    }
}


/// <summary>
/// 扩展方法 - 为PlotViewPanel添加便捷的数据适配功能
/// </summary>
public static class PlotViewPanelExtensions
{
    private static readonly Dictionary<PlotViewPanel, HighPerformanceDataAdapter> _adapters
        = new Dictionary<PlotViewPanel, HighPerformanceDataAdapter>();

    /// <summary>
    /// 连接到高性能解析器
    /// </summary>
    public static void ConnectToParser(this PlotViewPanel panel, UltraHighPerformanceChannelParser parser)
    {
        if (_adapters.ContainsKey(panel))
        {
            _adapters[panel].Stop();
            _adapters[panel].Dispose();
        }

        var adapter = new HighPerformanceDataAdapter(panel, parser);
        _adapters[panel] = adapter;
        adapter.Start();

        Console.WriteLine("[面板连接] 直方图面板已连接到解析器");
    }

    /// <summary>
    /// 断开解析器连接
    /// </summary>
    public static void DisconnectFromParser(this PlotViewPanel panel)
    {
        if (_adapters.ContainsKey(panel))
        {
            _adapters[panel].Stop();
            _adapters[panel].Dispose();
            _adapters.Remove(panel);

            Console.WriteLine("[面板断开] 直方图面板已断开解析器连接");
        }
    }

    /// <summary>
    /// 获取当前适配器状态
    /// </summary>
    public static bool IsConnectedToParser(this PlotViewPanel panel)
    {
        return _adapters.ContainsKey(panel);
    }

}